package org.jeecg.modules.strategy.component;

import com.alibaba.druid.util.StringUtils;
import org.jeecg.modules.strategy.model.query.AnalyticsQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import us.codecraft.webmagic.Spider;

@Component
public class MetaSpider {
    private final MetaPageProcessor metaPageProcessor;
    private final MetaPipeline metaPipeline;
    private final MetaDownloader metaDownloader;
    private Spider spider;

    @Autowired
    public MetaSpider(MetaPageProcessor metaPageProcessor,
                      MetaPipeline metaPipeline,
                      MetaDownloader metaDownloader) {
        this.metaPageProcessor = metaPageProcessor;
        this.metaPipeline = metaPipeline;
        this.metaDownloader = metaDownloader;
        this.spider = Spider.create(metaPageProcessor)
                .addPipeline(metaPipeline)
                .setDownloader(metaDownloader)
                .thread(5);
    }


    public String startCollectMetaTask(AnalyticsQuery analyticsQuery) {
        if (!StringUtils.isEmpty(analyticsQuery.getUrl())) {
            spider = this.spider.addUrl(analyticsQuery.getUrl());
            spider.run();
            return "success";
        }
        return "error";
    }

    public String stopCollectMetaTask() {
        if (spider != null) {
            spider.stop();
            return "success";
        }
        return "error";
    }
}
